<?php
App::uses('AppModel', 'Model');
/**
 * Link Model
 *
 * @property Case $Case
 */
class Link extends AdminAppModel {

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';


	//The Associations below have been created with all possible keys, those that are not needed can be removed


    public $actsAs = array('Containable');

    public $validate = array(
        'link_url' => array(
            'rule' => 'notEmpty',
        ),
        'link_name' => array(
            'rule' => 'notEmpty',
        ),
        'link_description' => array(
            'rule' => 'notEmpty',
        )
    );

    /**
     * 保存信息
     * @param array $req 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    public function saveLink($req, $isUpdate=false, $originData=array() )
    {
        // upload title_img
        $orginImage = isset($originData['link_image']) ? $originData['link_image'] : '';
        $icon = $this->_uploadIcon($req, $isUpdate, $orginImage);

        $data = array(
            'Link' => array(
                'link_url' => $req['link_url'],
                'link_name' => $req['link_name'],
                'link_image' => $icon,
                'link_description' => $req['link_description'],
                'link_rating' => $req['link_rating'],
                'link_notes' => $req['link_notes'],
                'updated' => time()
            )
        );
        if ($isUpdate) {
            $this->id = $req['id'];
        } else {
            $this->create();
        }
        if (!$this->save($data)) {
            throw new Exception("The data could not be saved.");
        }
    }
    
    /**
     * 处理标题的图片logo
     * @param array $requestData 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    private function _uploadIcon($requestData, $isUpdate=false, $orginImage='')
    {
        if ($isUpdate) {
            $orginImage = $orginData['link_image'];
        }
        $uploadFile = $this->upload($requestData['link_image'], 'link_image_', 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

}
